using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace GameForKids
{
    struct AnimationPlayer
    {

        public Animations Animations
        {
            get { return animations; }
        }
        Animations animations;


        //lay so thu tu frame
        public int FrameIndex
        {
            get { return frameIndex; }
        }
        int frameIndex;

        //thoi gian moi frame hien ra
        private float time;

        //lay goc toa do cua hinh
        public Vector2 Origin
        {
            get { return new Vector2(Animations.FrameWidth/2.0f, Animations.FrameHeight/2.0f); }
        }


        public void PlayAnimation(Animations animation)
        {
            // animation dang hoat dong
            if (Animations == animation)
                return;

            //neu khong hoat dong thi tao moi
            this.animations = animation;
            this.frameIndex = 0;
            this.time = 0.0f;
        }


        public void Draw(GameTime gameTime, SpriteBatch spriteBatch, Vector2 position, SpriteEffects spriteEffects, float rotate)
        {
            if (Animations == null)
                throw new NotSupportedException("No animation is currently playing.");
            time += (float)gameTime.ElapsedGameTime.TotalSeconds;
            //ve 
            while (time > Animations.FrameTime)
            {
                time -= Animations.FrameTime;
                if (Animations.IsLooping)
                {
                    frameIndex = (frameIndex + 1) % Animations.FrameCount;
                }
                else
                {
                    frameIndex = Math.Min(frameIndex + 1, Animations.FrameCount - 1);
                }
            }

            // khung hinh chua doi tuong hien tai
            Rectangle source = new Rectangle(FrameIndex * Animations.Texture.Height, 0, Animations.Texture.Height, Animations.Texture.Height);
            spriteBatch.Draw(Animations.Texture, position, source, Color.White, rotate, Origin, 1.0f, spriteEffects, 0.0f);
        }
    }
}
